<template>
  <div class="order-manage">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="searchForm.keyword"
          class="search-input"
          clearable
          placeholder="请输入商品名称或订单编号（以 ORD 开头的是订单编号）"
          @clear="handleSearch"
      />
      <el-button :icon="Search" type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 操作按钮栏 -->
    <div class="action-buttons">
      <el-button
          :disabled="multipleSelection.length === 0"
          :icon="Delete"
          type="danger"
          @click="handleBatchDelete"
      >
        批量删除
      </el-button>
    </div>

    <!-- 订单表格 -->
    <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <!-- 选择框 -->
      <el-table-column align="center" type="selection" width="55"/>

      <!-- 序号 -->
      <el-table-column align="center" label="序号" width="60">
        <template #default="{ $index }">
          {{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}
        </template>
      </el-table-column>

      <!-- 商品名称 -->
      <el-table-column label="商品名称" min-width="140" prop="productName" show-overflow-tooltip/>

      <!-- 订单编号 -->
      <el-table-column label="订单编号" prop="orderSn" show-overflow-tooltip width="160"/>

      <!-- 订单状态 -->
      <el-table-column align="center" label="订单状态" prop="status" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 总价 -->
      <el-table-column align="center" label="总价" prop="totalAmount" width="100">
        <template #default="{ row }">
          ¥{{ row.totalAmount }}
        </template>
      </el-table-column>

      <!-- 支付方式 -->
      <el-table-column align="center" label="支付方式" prop="payType" width="100">
        <template #default="{ row }">
          {{ getPayTypeText(row.payType) }}
        </template>
      </el-table-column>

      <!-- 收货地址 -->
      <el-table-column label="收货地址" min-width="200" prop="addressDetail" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.addressDetail || '地址信息未获取' }}
        </template>
      </el-table-column>

      <!-- 下单时间 -->
      <el-table-column label="下单时间" prop="createdAt" width="160">
        <template #default="{ row }">
          {{ row.createdAt || '未获取' }}
        </template>
      </el-table-column>

      <!-- 支付时间 -->
      <el-table-column label="支付时间" prop="payAt" show-overflow-tooltip width="160">
        <template #default="{ row }">
          {{ row.payAt || '未支付' }}
        </template>
      </el-table-column>

      <!-- 下单用户 -->
      <el-table-column label="下单用户" prop="username" width="120"/>

      <!-- 操作列 -->
      <el-table-column align="center" fixed="right" label="操作" width="100">
        <template #default="{ row }">
          <el-button
              size="small"
              style="color: #f56c6c;"
              type="text"
              @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Search} from '@element-plus/icons-vue'
import http from '@/request/Http.js'

// --- 响应式数据 ---
const loading = ref(false)
const tableData = ref([])
const multipleSelection = ref([])
const searchForm = reactive({
  keyword: ''
})
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// --- 方法 ---

// 获取订单列表（优化：智能判断 orderSn 或 productName）
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
    }

    const keyword = searchForm.keyword.trim()

    if (keyword) {
      // ✅ 智能判断：以 ORD 开头 -> 订单编号查询 (只传 orderSn)
      if (keyword.toUpperCase().startsWith('ORD')) {
        params.orderSn = keyword
        params.productName = '' // 不传商品名称
      } else {
        // ❗ 否则 -> 商品名称查询 (只传 productName)
        params.productName = keyword
        params.orderSn = '' // 不传订单编号
      }
    } else {
      // 如果关键词为空，不传任何条件，查询全部（未删除的）
      params.orderSn = ''
      params.productName = ''
    }

    const res = await http.get('/Order/getAllOrder', {params})

    console.log('后端返回的数据：', res.data)
    if (res.code === 200) {
      const pageData = res.data
      tableData.value = pageData.records || []
      pagination.total = pageData.total || 0
      pagination.currentPage = pageData.current || 1
      pagination.pageSize = pageData.size || 10
    } else {
      ElMessage.error(res.msg || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败，请检查网络')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTableData()
}

// 重置
const handleReset = () => {
  searchForm.keyword = ''
  pagination.currentPage = 1
  getTableData()
}

// 选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  getTableData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getTableData()
}

// 删除单条订单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定删除订单 "${row.orderSn}" 吗？`, '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    const res = await http.delete(`/Order/deleteOrder/${row.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getTableData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败或取消操作')
    }
  }
}

// 批量删除订单
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的订单')
    return
  }
  try {
    await ElMessageBox.confirm(
        `确定删除选中的 ${multipleSelection.value.length} 条订单吗？`,
        '提示',
        {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
    )
    const ids = multipleSelection.value.map((item) => item.id)
    const res = await http.post('/Order/batchDeleteOrders', ids)
    if (res.code === 200) {
      ElMessage.success('批量删除成功')
      getTableData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败或取消操作')
    }
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    1: '待付款',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已取消'
  }
  return map[status] || '未知'
}

// 获取状态标签类型
const getStatusType = (status) => {
  const map = {
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success',
    5: 'danger'
  }
  return map[status] || 'info'
}

// 获取支付方式显示文本
const getPayTypeText = (payType) => {
  const payTypeMap = {
    wechat: '微信',
    alipay: '支付宝'
  }
  return payTypeMap[payType] || '未支付'
}

// 组件挂载时加载数据
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.order-manage {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>